﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using EKETEAM.UserControl;
using System.Xml;
using System.Xml.Serialization;

namespace eFrameWork.Manage
{
    public partial class Models : System.Web.UI.Page
    {
        public eList elist;
        public eForm edt;
        public eAction Action;
        public eFormControl f2 = new eFormControl("f2");
        public eUser user;
        string sql = "";
        eFormControl f7 = new eFormControl("f7");
        private DataTable _modelids;
        public DataTable ModelIDS
        {
            get
            {
                if (_modelids == null)
                {
                    _modelids = eBase.DataBase.getDataTable("select ModelID,ParentID from a_eke_sysModels where delTag=0");
                }
                return _modelids;
            }
        }
        public string getLabels(string ids)
        {
            if (ids.Length == 0) return "";
            string sql = "select mc from a_eke_sysLabels where LableID in ('" + ids.Replace(",","','") + "')";
            DataTable tb = eBase.DataBase.getDataTable(sql);
            string text = "";
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                if (i > 0) text += "、";
                text += tb.Rows[i]["mc"].ToString();
            }
            return text;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser("Manage");
            Action = new eAction();
            
            edt = new eForm("a_eke_sysModels", user);
            //edt.AutoRedirect = false;
            edt.AddControl(f1);//名称
            f2.Field = "Code";
            edt.AddControl(f2);//编码
            edt.AddControl(f3);//简介
            edt.AddControl(f4);//文件名
            edt.AddControl(f41);//文件名
            edt.AddControl(f5);//自动
            edt.AddControl(f6);//类名
            //if (f5.Value.ToString().ToLower() == "true")
            //{
                f7.Field = "ParentID";
                f7.FieldType = "uniqueidentifier";
                edt.AddControl(f7);//上级
            //}

            edt.AddControl(f8);//关系
            edt.AddControl(f9);//类型
            edt.AddControl(f10);//数据源
            edt.AddControl(f11);//标签
            edt.AddControl(f12);//是否基础模块
            edt.AddControl(f13);//基础模块
            edt.AddControl(f14);//网站模块
            edt.AddControl(f15);//网站栏目
            if (Action.Value == "gettables")
            {
                string modeltype = eParameters.QueryString("modeltype");
                DataTable dt;
                string dsid = eParameters.QueryString("dsid");
                if (dsid.Length > 0)
                {

                    eDataBase DB = new eDataBase(new Guid(dsid));
                    dt = modeltype == "1" ? DB.getSchemaTables() : DB.getSchemaTableViews();
                }
                else
                {
                    dt = modeltype == "1" ? eBase.DataBase.getSchemaTables() : eBase.DataBase.getSchemaTableViews();
                }
                Response.Write(dt.toJSON());
                Response.End();
            }
            if (Action.Value == "active") //是否显示
            {
            
                sql = eParameters.Replace("update a_eke_sysModels set Finsh='{querystring:value}' where ModelID='{querystring:id}'", null, null);
                eBase.DataBase.Execute(sql);
                eBase.clearDataCache("a_eke_sysModels"); //清除缓存
               

                Response.Redirect(Request.ServerVariables["HTTP_REFERER"] == null ? "Default.aspx" : Request.ServerVariables["HTTP_REFERER"].ToString(), true);
                eBase.End();
            }
            if (Action.Value == "del")
            {
                string id = eParameters.QueryString("id");
                string ids = getids(id);
                //ids = "'" + ids.Replace(",", "','") + "'";
                string deltype = eParameters.QueryString("deltype");

                foreach (string _id in ids.Split(",".ToCharArray()))
                {
                    if (deltype == "2")
                    {
                        //string code = eBase.DataBase.getValue("select code from a_eke_sysModels where ModelID='" + _id + "'");//code为mysql关键词
                        string code = eBase.DataBase.eList("a_eke_sysModels").Fields.Add("code").Where.Add("ModelID='" + _id + "'").getValue();
                        if (code.ToLower().IndexOf("a_eke_sys") == -1 && code.Length > 0)
                        {
                            eBase.DataBase.Execute("drop table " + eBase.DataBase.StartNameSplitChar + code + eBase.DataBase.EndNameSplitChar);
                        }
                    }
                    if (deltype == "4")
                    {
                        string aspxfile = eBase.DataBase.getValue("select AspxFile from a_eke_sysModels where ModelID='" + _id + "'");
                        string basepath = Server.MapPath("~");
                        if (aspxfile.Length > 0)
                        {
                            string filepath = basepath + aspxfile.Replace("..", "").Replace("/", "\\");
                            if (System.IO.File.Exists(filepath))
                            {
                                //eBase.Writeln(filepath);
                                try
                                {
                                    System.IO.File.Delete(filepath);
                                }
                                catch
                                { }
                            }
                            filepath += ".cs";
                            if (System.IO.File.Exists(filepath))
                            {
                                //eBase.Writeln(filepath);
                                try
                                {
                                    System.IO.File.Delete(filepath);
                                }
                                catch
                                { }
                            }                            
                        }
                        aspxfile = eBase.DataBase.getValue("select mAspxFile from a_eke_sysModels where ModelID='" + _id + "'");
                        if (aspxfile.Length > 0)
                        {
                            string filepath = basepath + aspxfile.Replace("..", "").Replace("/", "\\");
                            if (System.IO.File.Exists(filepath))
                            {
                                //eBase.Writeln(filepath);
                                try
                                {
                                    System.IO.File.Delete(filepath);
                                }
                                catch
                                { }
                            }
                            filepath += ".cs";
                            if (System.IO.File.Exists(filepath))
                            {
                                //eBase.Writeln(filepath);
                                try
                                {
                                    System.IO.File.Delete(filepath);
                                }
                                catch
                                { }
                            }      
                        }
                    }
                    eBase.DataBase.Execute("delete from a_eke_sysModels where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysModelItems where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysModelConditions where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysModelConditionItems where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysConditions where ModelID='" + _id + "'");
                    eBase.UserInfoDB.Execute("delete from a_eke_sysPowers where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysActions where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysModelTabs where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysModelPanels where ModelID='" + _id + "'");
                    eBase.UserInfoDB.Execute("delete from a_eke_sysUserCustoms where ModelID='" + _id + "'");
                    eBase.UserInfoDB.Execute("delete from a_eke_sysUserColumns where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysCheckUps where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysApplicationItems where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysReports where ModelID='" + _id + "'");
                    eBase.DataBase.Execute("delete from a_eke_sysReportItems where ModelID='" + _id + "'");

                }

                eBase.clearDataCache(); //清除所有缓存

                if (Request.ServerVariables["HTTP_REFERER"] == null)
                {
                    Response.Redirect("Models.aspx", true);
                }
                else
                {
                    Response.Redirect(Request.ServerVariables["HTTP_REFERER"].ToString(), true);
                }
                Response.End();
                //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
            }
            edt.onChange += new eFormTableEventHandler(edt_onChange);
            edt.Handle();

           
            Action.Actioning += new eActionHandler(Action_Actioning);
            Action.Listen();
        }
        public void edt_onChange(object sender, eFormTableEventArgs e)
        {
            if (e.eventType == eFormTableEventType.Inserting)
            {
                if (user["ServiceID"].Length > 0) edt.Fields.Add("ServiceID", user["ServiceID"]);
            }
            string type = eParameters.Form("f9");
            if (type == "2") return;
            string formtable = eParameters.Form("formtable");
            string tablename = eParameters.Form("f2");
            string parentid = eParameters.Form("f7");
            string sql = "";
            if (e.eventType == eFormTableEventType.Inserted || e.eventType == eFormTableEventType.Updated)
            {
                sql="update a set a.submodel=(case when isnull(b.type,2)=1 then 1 else 0 end) ";
                sql +=" FROM a_eke_sysModels a ";
                sql +=" left join a_eke_sysModels b on a.ParentID=b.ModelID ";
                sql += " where a.ModelID='" + e.ID + "'";
                sql = "update a_eke_sysModels set submodel=(case when ParentID is null then 0 else 1 end) where ModelID='" + e.ID + "'";
                eBase.DataBase.Execute(sql);
            }
            #region 添加OK
            if (e.eventType == eFormTableEventType.Inserted)
            {
                if (type == "4") //报表模块
                {
                    eBase.DataBase.Execute("update a_eke_sysModels set Power='[{\"text\":\"列表\",\"value\":\"list\"}]' where ModelID='" + e.ID + "'");
                    return;
                }
                #region 新建表

                if (formtable.Length == 0 && tablename.Length > 0)
                {
                    string dsid = eParameters.Form("f10");
                    eDataBase db=null;
                    if (dsid.Length > 5) db = new eDataBase(new Guid(dsid));
                    if (db == null)
                    {
                        eBase.DataBase.CreateDefaultTable(tablename, eParameters.Form("f1"));
                    }
                    else
                    {
                        db.CreateDefaultTable(tablename, eParameters.Form("f1"));
                    }
                }
                #endregion
                if (eBase.parseBool(f5.Value) && tablename.Length > 0) //自动模块
                {

                    object db = null;
                    string dsid = eParameters.Form("f10");
                    string joinmore = eParameters.Form("f8");
                    if (dsid.Length > 5) db = new eDataBase(new Guid(dsid));
                    #region 添加模块
                    DataTable tb = db == null ? eBase.DataBase.getSchemaColumns(tablename) : (db as eDataBase).getSchemaColumns(tablename); 

                    //eBase.PrintDataTable(tb);

                    string zj = db == null ? eBase.DataBase.getPrimaryKey(tablename) : (db as eDataBase).getPrimaryKey(tablename);
                    string syscolumns = eConfig.getAllSysColumns() + "," + zj.ToLower() + ",";
                    //eBase.Writeln(zj);
                    //eBase.Writeln(syscolumns);
                    int Num = 1;
                    string frmName = "";
                    #region 序号列
                    if (parentid.Length == 0)
                    {
                        frmName = "M" + e.ID.Substring(0, 2) + "_" + "F" + Num.ToString();
                        //sql = "insert into a_eke_sysModelItems (ModelItemID,frmName,frmID,Num,ListOrder,ModelID,MC,ListHTML,Custom,showList,mShowList,ListWidth,mListWidth,Move,Size) ";
                        //sql += " values ('" + Guid.NewGuid().ToString() + "','" + frmName + "','" + frmName + "','" + Num.ToString() + "','" + Num.ToString() + "','" + e.ID + "','序号','{row:index}',1," + (f7.Value.ToString().Length > 0 ? "0" : "1") + ",1,'60','60',1,1)";
                        //eBase.DataBase.Execute(sql);

                        eBase.DataBase.eTable("a_eke_sysModelItems")
                            .Fields.Add("ModelItemID", Guid.NewGuid().ToString())
                            .Fields.Add("frmName", frmName)
                            .Fields.Add("frmID", frmName)
                            .Fields.Add("Num", Num)
                            .Fields.Add("ListOrder", Num)
                            .Fields.Add("ModelID", e.ID)
                            .Fields.Add("MC", "序号")
                            .Fields.Add("ListHTML", "{row:index}")
                            .Fields.Add("Custom", 1)
                            .Fields.Add("showList", f7.Value.ToString().Length > 0 ? 0 : 1)
                            .Fields.Add("mShowList", f7.Value.ToString().Length > 0 ? 0 : 1)
                            .Fields.Add("ListWidth", 60)
                            .Fields.Add("mListWidth", 60)
                            .Fields.Add("Move", 1)
                            .Fields.Add("Size", 1)
                            .Add();
                        //eBase.AppendLog(sql);
                        Num++;
                    }
                    #endregion
                   
                    #region 其他列
                    // eBase.Writeln(tb.Rows.Count.ToString());
                    foreach (DataRow dr in tb.Rows)
                    {
                        string sys = (syscolumns.IndexOf("," + dr["COLUMN_NAME"].ToString().ToLower() + ",") > -1 ? "1" : "0");
                        string showedit = (sys == "0" ? "1" : "0");
                        string showlist = (sys == "0" ? "1" : "0");


                        frmName = "M" + e.ID.Substring(0, 2) + "_" + "F" + Num.ToString();
                        eTable etb = new eTable("a_eke_sysModelItems");

                        if (",siteid,orgcode,usercode,postlevel,dataflags,checkupcode,checkuptext,".IndexOf("," + dr["COLUMN_NAME"].ToString().ToLower() + ",") > -1)
                        {
                            showlist = "0";
                            showedit = "0";      
                        }
                        if (dr["COLUMN_NAME"].ToString().ToLower().EndsWith("eng"))
                        {
                            showlist = "0";
                            showedit = "0"; 
                        }
                        if (dr["COLUMN_NAME"].ToString().ToLower() == "siteid_bak")
                        {
                            showlist = "0";
                            showedit = "1";
                            etb.Fields.Add("ControlType", "hidden");
                            etb.Fields.Add("addControlType", "hidden");
                            etb.Fields.Add("editControlType", "hidden");
                            etb.Fields.Add("defaultvalue", "{user:SiteID}");
                        }

                        etb.Fields.Add("ModelID", e.ID);
                        etb.Fields.Add("Num", Num.ToString());
                        etb.Fields.Add("MC", dr["DESCRIPTION"].ToString());
                        etb.Fields.Add("Code", dr["COLUMN_NAME"].ToString());
                        etb.Fields.Add("Type", dr["DATA_TYPE"].ToString());
                        etb.Fields.Add("Length", dr["CHARACTER_MAXIMUM_LENGTH"].ToString());
                        etb.Fields.Add("Sys", sys);
                        etb.Fields.Add("PX", dr["ORDINAL_POSITION"].ToString());
                        etb.Fields.Add("primaryKey", (zj.ToLower() == dr["COLUMN_NAME"].ToString().ToLower() ? "1" : "0"));

                        #region 客户端验证
                        //

                        if (dr["DATA_TYPE"].ToString().ToLower().IndexOf("uniqueidentifier") > -1)
                        {
                            etb.Fields.Add("minlength", "36");
                            etb.Fields.Add("maxlength", "36");
                        }
                        if (dr["DATA_TYPE"].ToString().ToLower().IndexOf("int") > -1)
                        {
                            etb.Fields.Add("datatype", "int");
                        }
                        if (dr["DATA_TYPE"].ToString().ToLower().IndexOf("date") > -1)
                        {
                            etb.Fields.Add("datatype", "date");
                        }
                        if (",float,numeric,decimal,".IndexOf("," + dr["DATA_TYPE"].ToString().ToLower() + ",") > -1)
                        {
                            etb.Fields.Add("datatype", "float");
                        }
                        #endregion
                        if (dr["COLUMN_NAME"].ToString().ToLower() == "addtime" && parentid.Length == 0)
                        {
                            showlist = "1";
                        }
                       
                        if (parentid.Length > 0 && joinmore=="0") //1v1
                        {
                            showlist = "0";
                            showedit = "0";
                        }
                        if (zj.ToLower() == dr["COLUMN_NAME"].ToString().ToLower())//主键
                        {
                            showlist = "0";
                            showedit = "0";
                        }
                        etb.Fields.Add("ShowList", showlist);
                        etb.Fields.Add("mShowList", showlist);
                        etb.Fields.Add("ShowView", showedit);
                        etb.Fields.Add("ShowAdd", showedit);
                        etb.Fields.Add("ShowEdit", showedit);

                        if (parentid.Length == 0) //主模块
                        {
                            etb.Fields.Add("OrderBy", showlist);
                            etb.Fields.Add("Move", showlist);
                            etb.Fields.Add("Size", showlist);
                        }

                        if (dr["DATA_TYPE"].ToString().ToLower().IndexOf("char") > -1)
                        {
                            if( dr["CHARACTER_MAXIMUM_LENGTH"].ToString()!="-1") etb.Fields.Add("maxLength", dr["CHARACTER_MAXIMUM_LENGTH"].ToString());
                            etb.Fields.Add("Width", "300");
                        }
                        if (dr["DATA_TYPE"].ToString().ToLower().IndexOf("date") > -1)
                        {
                            etb.Fields.Add("ControlType", "date");
                            etb.Fields.Add("addControlType", "date");
                            etb.Fields.Add("editControlType", "date");
                            etb.Fields.Add("formatstring", (dr["DATA_TYPE"].ToString().ToLower().IndexOf("datetime") > -1 ? "{0:yyyy-MM-dd HH:mm}" : "{0:yyyy-MM-dd}"));
                            etb.Fields.Add("dateformat", (dr["DATA_TYPE"].ToString().ToLower().IndexOf("datetime") > -1 ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"));
                        }
                        if (dr["DATA_TYPE"].ToString().ToLower() == "bit")
                        {
                            if (sys == "0") etb.Fields.Add("defaultvalue", "1");
                            etb.Fields.Add("ControlType", "radio");
                            etb.Fields.Add("addControlType", "radio");
                            etb.Fields.Add("editControlType", "radio");
                            etb.Fields.Add("Options", "[{\"text\":\"是\",\"value\":\"1\"},{\"text\":\"否\",\"value\":\"0\"}]");


                        }
                        if (dr["DATA_TYPE"].ToString().ToLower() == "text" || dr["DATA_TYPE"].ToString().ToLower() == "ntext")
                        {
                            etb.Fields.Add("ControlType", "html");
                            etb.Fields.Add("addControlType", "html");
                            etb.Fields.Add("editControlType", "html");
                        }
                        if (dr["COLUMN_NAME"].ToString().ToLower() == "show")
                        {

                            //sql = "insert into a_eke_sysActions (ModelID,MC,Action,SQL) values ('" + e.ID + "','是否显示','show','update " + tablename + " set show=''{querystring:value}'' where " + zj + "=''{querystring:id}''')";
                            //sql = "insert into a_eke_sysActions (ActionID,ModelID,MC,Action,SQL) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','是否显示','show','update {table} set show=''{querystring:value}'' where {pk}=''{querystring:id}''')";
                            //eBase.DataBase.Execute(sql);

                            eBase.DataBase.eTable("a_eke_sysActions")
                                .Fields.Add("ActionID",Guid.NewGuid().ToString())
                                .Fields.Add("ModelID", e.ID)
                                .Fields.Add("MC", "是否显示")
                                .Fields.Add("Action", "show")
                                .Fields.Add("SQL", "update {table} set show='{querystring:value}' where {pk}='{querystring:id}'")
                                .Add();


                            etb.Fields.Add("ListHTML", "<a href=\"{base:url}act=show&id={data:id}&value={data:showvalue}\"><img src=\"{base:virtualpath}{data:ShowPIC}\" border=\"0\"></a>");

                            eBase.DataBase.Execute("update a_eke_sysModels set ListFields='CASE WHEN Show=1 THEN ''images/sw_true.gif'' ELSE ''images/sw_false.gif'' END as ShowPIC,CASE WHEN Show=1 THEN ''0'' ELSE ''1'' END as ShowValue' where ModelID='" + e.ID + "'"); //,CASE WHEN ZD=1 THEN ''<img src=\"images/sw_true.gif\" border=\"0\">'' ELSE ''<img src=\"images/sw_false.gif\" border=\"0\">'' END as ZDPIC,CASE WHEN ZD=1 THEN ''0'' ELSE ''1'' END as ZDValue


                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditions (ModelConditionID,ModelID,MC,ControlType) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','是否显示','radio')");
                            //string condid = eBase.DataBase.ID;

                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditionItems (ModelConditionItemID,ModelID,ModelConditionID,MC,ConditionValue) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','" + condid + "','是','show=1')");
                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditionItems (ModelConditionItemID,ModelID,ModelConditionID,MC,ConditionValue) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','" + condid + "','否','show=0')");

                            string MaxConds = eBase.DataBase.getValue("select count(1)+1 from a_eke_sysModelConditions where ModelID='" + e.ID + "'");
                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditions (ModelConditionID,ModelID,MC,ControlType,Code,Operator,Options,Num) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','是否显示','radio','show','=','[{\"text\":\"是\",\"value\":\"1\"},{\"text\":\"否\",\"value\":\"0\"}]','" + MaxConds + "')");
                            eBase.DataBase.eTable("a_eke_sysModelConditions")
                                .Fields.Add("ModelConditionID", Guid.NewGuid().ToString())
                                .Fields.Add("ModelID", e.ID)
                                .Fields.Add("MC", "是否显示")
                                .Fields.Add("ControlType", "radio")
                                .Fields.Add("Code", "show")
                                .Fields.Add("Operator", "=")
                                .Fields.Add("Options", "[{\"text\":\"是\",\"value\":\"1\"},{\"text\":\"否\",\"value\":\"0\"}]")
                                .Fields.Add("Num", MaxConds)
                                .Add();
                            
                            //eBase.DataBase.Execute("update a_eke_sysModels set MaxConds='" + MaxConds + "' where ModelID='" + e.ID + "'");
                            eBase.DataBase.eTable("a_eke_sysModels").Fields.Add("MaxConds", MaxConds).Update("ModelID='" + e.ID + "'");
                        }
                        if (dr["COLUMN_NAME"].ToString().ToLower() == "deltag")
                        {
                            //etb.Fields.Add("Condition", "=");
                            //etb.Fields.Add("ConditionValue", "0");
                        }
                        if (dr["COLUMN_NAME"].ToString().ToLower() == "addtime" && parentid.Length==0)
                        {
                            //etb.Fields.Add("defaultOrder", "2");
                            string MaxConds = eBase.DataBase.getValue("select count(1)+1 from a_eke_sysModelConditions where ModelID='" + e.ID + "'");
                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditions (ModelConditionID,ModelID,MC,ControlType,Code,Operator,DateFormat,Width,Num) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','添加时间','date','addTime','>=','yyyy-MM-dd','150','" + MaxConds + "')");
                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditions (ModelConditionID,ModelID,MC,ControlType,Code,Operator,DateFormat,Width,Num) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','添加时间','date','addTime','<=','yyyy-MM-dd','150'," + MaxConds + " + 1)");

                            //eBase.DataBase.Execute("insert into a_eke_sysModelConditions (ModelConditionID,ModelID,MC,ControlType,Code,Operator,DateFormat,Width,Num) values ('" + Guid.NewGuid().ToString() + "','" + e.ID + "','创建时间','dateregion','addTime','','yyyy-MM-dd','150','" + MaxConds + "')");
                            eBase.DataBase.eTable("a_eke_sysModelConditions")
                               .Fields.Add("ModelConditionID", Guid.NewGuid().ToString())
                               .Fields.Add("ModelID", e.ID)
                               .Fields.Add("MC", "创建时间")
                               .Fields.Add("ControlType", "dateregion")
                               .Fields.Add("Code", "addTime")
                               .Fields.Add("Operator", "=")
                               .Fields.Add("DateFormat", "yyyy-MM-dd")
                               .Fields.Add("Width", 150)
                               .Fields.Add("Num", MaxConds)
                               .Add();
                            
                            //eBase.DataBase.Execute("update a_eke_sysModels set MaxConds='" + MaxConds + "' where ModelID='" + e.ID + "'");
                            eBase.DataBase.eTable("a_eke_sysModels").Fields.Add("MaxConds", MaxConds).Update("ModelID='" + e.ID + "'");
                        }
                        etb.Fields.Add("frmName", frmName);
                        etb.Fields.Add("frmID", frmName);
                        etb.Fields.Add("notnull", showedit);
                        etb.Fields.Add("ListOrder", Num.ToString());
                        etb.Add();



                        Num++;
                    }
                    #endregion
                    #region 操作列
                    if (parentid.Length == 0 && type != "10")
                    {
                        frmName = "M" + e.ID.Substring(0, 2) + "_" + "F" + Num.ToString();
                        //sql = "insert into a_eke_sysModelItems (ModelItemID,frmName,frmID,Num,ListOrder,ModelID,MC,ListHTML,Custom,showList,mShowList,ListWidth,mListWidth,Move,Size) ";
                        //sql += " values ('" + Guid.NewGuid().ToString() + "','" + frmName + "','" + frmName + "','" + Num.ToString() + "','" + Num.ToString() + "','" + e.ID + "','操作','<a href=\"{base:url}act=view&id={data:ID}\">查看</a><a href=\"{base:url}act=edit&id={data:ID}\">修改</a><a href=\"{base:url}act=del&id={data:ID}\" onclick=\"javascript:return confirm(''确认要删除吗？'');\">删除</a>',1," + (f7.Value.ToString().Length > 0 ? "0" : "1") + ",1,'130','130',1,1)";
                        if (type == "5") //流水报表模块
                        {
                            //sql = "insert into a_eke_sysModelItems (ModelItemID,frmName,frmID,Num,ListOrder,ModelID,MC,ListHTML,Custom,showList,mShowList,ListWidth,mListWidth,Move,Size) ";
                            //sql += " values ('" + Guid.NewGuid().ToString() + "','" + frmName + "','" + frmName + "','" + Num.ToString() + "','" + Num.ToString() + "','" + e.ID + "','操作','<a href=\"{base:url}act=view&id={data:ID}\">查看</a>',1," + (f7.Value.ToString().Length > 0 ? "0" : "1") + ",1,'130','130',1,1)";
                        }
                        //eBase.DataBase.Execute(sql);
                        eBase.DataBase.eTable("a_eke_sysModelItems")
                              .Fields.Add("ModelItemID", Guid.NewGuid().ToString())
                              .Fields.Add("frmName", frmName)
                              .Fields.Add("frmID", frmName)
                              .Fields.Add("Num", Num)
                              .Fields.Add("ListOrder", Num)
                              .Fields.Add("ModelID", e.ID)
                              .Fields.Add("MC", "操作")
                              .Fields.Add("ListHTML", type == "5" ? "<a href=\"{base:url}act=view&id={data:ID}\">查看</a>" : "<a href=\"{base:url}act=view&id={data:ID}\">查看</a><a href=\"{base:url}act=edit&id={data:ID}\">修改</a><a href=\"{base:url}act=del&id={data:ID}\" onclick=\"javascript:return confirm('确认要删除吗？');\">删除</a>")
                              .Fields.Add("Custom", 1)
                              .Fields.Add("showList", f7.Value.ToString().Length > 0 ? 0 : 1)
                              .Fields.Add("mShowList", f7.Value.ToString().Length > 0 ? 0 : 1)
                              .Fields.Add("ListWidth", 130)
                              .Fields.Add("mListWidth", 130)
                              .Fields.Add("Move", 1)
                              .Fields.Add("Size", 1)
                              .Add();

          
                            
                       
                    }
                    #endregion
                    //eBase.DataBase.Execute("update a_eke_sysModels set MaxItems='" + Num.ToString() + "' where ModelID='" + e.ID + "'");   
                    eBase.DataBase.eTable("a_eke_sysModels").Fields.Add("MaxItems", Num).Update("ModelID='" + e.ID + "'");
                    #region 默认条件、排序
                   

                    //DataRow[] rows = tb.Select("COLUMN_NAME='siteid'");
                    /*
                    if (f7.Value.ToString().Length == 0) //主模块
                    {
                        eBase.DataBase.Execute("update a_eke_sysModels set DefaultCondition='" + (rows.Length == 0 ? "" : "SiteID=''{user:SiteID}'' and ") + "delTag=0 ',DefaultOrderby='addTime Desc' where ModelID='" + e.ID + "'");
                    }
                    else
                    {
                        eBase.DataBase.Execute("update a_eke_sysModels set DefaultCondition='" + (rows.Length == 0 ? "" : "SiteID=''{user:SiteID}'' and ") + " delTag=0',DefaultOrderby='addTime' where ModelID='" + e.ID + "'");
                    }
                    */
                    DataRow[] rows = tb.Select("COLUMN_NAME='addtime'");
                    if (rows.Length > 0)
                    {
                        sql = "update a_eke_sysModels set DefaultOrderby='addTime" + (f7.Value.ToString().Length == 0 ? " Desc" : "") + "' where ModelID='" + e.ID + "'";
                        eBase.DataBase.Execute(sql);
                    }
                    rows = tb.Select("COLUMN_NAME='deltag'");
                    if (rows.Length > 0)
                    {
                        rows = tb.Select("COLUMN_NAME='siteid'");
                        sql = "update a_eke_sysModels set DefaultCondition='" + (rows.Length > 0 ? "SiteID={user:SiteID} and " : "") + "delTag=0' where ModelID='" + e.ID + "'";
                        eBase.DataBase.Execute(sql);
                    }

                    #endregion
                    string power = "[{\"text\":\"列表\",\"value\":\"list\"},{\"text\":\"详细\",\"value\":\"view\"},{\"text\":\"添加\",\"value\":\"add\"},{\"text\":\"编辑\",\"value\":\"edit\"},{\"text\":\"删除\",\"value\":\"del\"}]";
                    if (type == "5") power = "[{\"text\":\"列表\",\"value\":\"list\"},{\"text\":\"详细\",\"value\":\"view\"}]";
                    if (type == "10") power = "[{\"text\":\"列表\",\"value\":\"list\"},{\"text\":\"导出\",\"value\":\"export\"}]";

                    eBase.DataBase.Execute("update a_eke_sysModels set Power='" + power + "' where ModelID='" + e.ID + "'");//,{text:复制,value:copy},{text:打印,value:print},{text:导入,value:import}
                    #endregion
                }
                else
                {
                    eBase.DataBase.Execute("update a_eke_sysModels set Power='[{\"text\":\"列表\",\"value\":\"list\"},{\"text\":\"详细\",\"value\":\"view\"},{\"text\":\"添加\",\"value\":\"add\"},{\"text\":\"编辑\",\"value\":\"edit\"},{\"text\":\"删除\",\"value\":\"del\"}]' where ModelID='" + e.ID + "'");
                }
            }
            #endregion
            #region 修改
            if (e.eventType == eFormTableEventType.Updating)
            {
                //string oldName = eBase.DataBase.getValue("select code from a_eke_sysModels where ModelID='" + e.ID + "'");
                string oldName = eBase.DataBase.eList("a_eke_sysModels").Where.Add("ModelID='" + e.ID + "'").getValue("code");
                if (oldName.ToLower() != tablename.ToLower())
                {
                    eBase.DataBase.Execute("exec sp_rename  '" + oldName + "' ,'" + tablename + "'");
                }
            }
            #endregion
        }
        private void List()
        {
            elist = new eList("a_eke_sysModels");
            //elist.Fields.Add("*");
            elist.Fields.Add("ModelID,MC,Type,Auto,Code,AspxFile,mAspxFile,LabelIDS,SM,addTime");
            elist.Fields.Add("CASE WHEN Finsh=1 THEN 'images/sw_true.gif' ELSE 'images/sw_false.gif' END as ShowPIC,CASE WHEN Finsh=1 THEN '0' ELSE '1' END as ShowValue");
            //elist.Where.Add("delTag=0 and (type=1 or type=4 or type=5) and subModel=0");
            elist.Where.Add("delTag=0 and Type!=2 and subModel=0");
            elist.Where.Add("ServiceID" + (user["ServiceID"].Length == 0 ? " is null" : "='" + user["ServiceID"] + "'"));

            elist.Where.Add(eSearchControlGroup);
            elist.OrderBy.Add("addTime desc");
            //eBase.Writeln(elist.SQL);
            //eBase.End();
            elist.Bind(Rep, ePageControl1);
        }
        //来源ModelItems
        private string getModelTree(string pid, string node,string value)
        {
            string sql = "Select ModelID,MC from a_eke_sysModels where delTag=0 ";
            //sql += " and ParentID " + (pid.Length > 0 ? "='" + pid + "'" : "is NULL");
            if (pid.Length > 0)
            {
                sql += "and ParentID='" + pid + "'";
            }
            else
            {
                sql += " and ParentID is null";
            }
            if (value.Length > 0)
            {
                sql += " and (type=1 or type=2)";
            }
            else
            {
                sql += " and Auto=1 and type in (1,3)";// and type=1
            }

            string id = eParameters.QueryString("id");
            if (id.Length > 0) sql += " and ModelID!='" + id + "'";
            sql += " order by addTime desc";
            //eBase.AppendLog(sql);


            DataTable dt = eBase.DataBase.getDataTable(sql);
            if (dt.Rows.Count == 0) return "";
            string temp = "";
            if (pid.Length == 0) temp = "<option value=\"\">请选择</option>\r\n";
            foreach (DataRow dr in dt.Rows)
            {
                temp += "<option value=\"" + dr["ModelID"].ToString() + "\"" + (dr["ModelID"].ToString()==value ? " selected=\"true\"" : "") + ">" + node + dr["mc"].ToString() + "</option>\r\n";
                temp += getModelTree(dr["ModelID"].ToString(), node + "&nbsp;&nbsp;",value);
            }
            return temp;

        }
        public string getids(string modelid)
        {
            if (Request.QueryString["single"] != null) return modelid;//复制单个模块，不包括子模块
            DataRow[] rows = ModelIDS.Select("Convert(ParentID, 'System.String')='" + modelid + "'");
            if (rows.Length == 0)
            {
                return modelid;
            }
            else
            {
                foreach (DataRow dr in rows)
                {
                    modelid += "," + getids(dr["modelid"].ToString());
                }
            }
            return modelid;
        }
        /// <summary>
        /// 创建步骤
        /// </summary>
        /// <param name="modelid"></param>
        private void CreateStep(string modelid)
        {
            string ModelID = modelid;
            string name = eParameters.QueryString("name");
            string newModelID = Guid.NewGuid().ToString();

            //Response.Write(modelid + "::" + name + ":::" + newModelID);

            #region  生成关系
            eList a_eke_sysModels = new eList("a_eke_sysModels");
            a_eke_sysModels.Where.Add("deltag=0");
            a_eke_sysModels.Where.Add("modelid='" + modelid + "'");

            eList a_eke_sysModelItems = new eList("a_eke_sysModelItems");
            a_eke_sysModelItems.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelItems);

            eList a_eke_sysModelTabs = new eList("a_eke_sysModelTabs");
            a_eke_sysModelTabs.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelTabs);

            eList a_eke_sysModelPanels = new eList("a_eke_sysModelPanels");
            a_eke_sysModelPanels.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelPanels);
            #endregion

            #region 获取数据
            DataTable Models = a_eke_sysModels.getDataTable();
            //eBase.PrintDataTable(Models);

            DataTable ModelItems = a_eke_sysModelItems.getDataTable();
           // eBase.PrintDataTable(ModelItems);



            DataTable ModelTabs = a_eke_sysModelTabs.getDataTable();
            //eBase.PrintDataTable(ModelTabs);


            DataTable ModelPanels = a_eke_sysModelPanels.getDataTable();
            //eBase.PrintDataTable(ModelPanels);
            #endregion

            #region 数据处理
            DataRow[] rows;
            foreach (DataRow dr in Models.Rows)
            {
                dr["subModel"] = 1;
                dr["ModelID"] = newModelID;
                dr["ParentID"] = modelid;
                dr["mc"] = name;
                dr["Type"] = "8";
                dr["addtime"] = DateTime.Now;





                rows = ModelItems.Select("BindModelID='" + ModelID + "'");
                rows.UpdateForeignKey("BindModelID", ModelID, newModelID, true);

                rows = ModelItems.Select("FillModelID='" + ModelID + "'");
                rows.UpdateForeignKey("FillModelID", ModelID, newModelID, true);







                rows = ModelItems.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelItemID = _dr["ModelItemID"].ToString();
                    string _newModelItemID = Guid.NewGuid().ToString();
                    DataRow[] rs = ModelItems.Select("FillItem='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillItem", _ModelItemID, _newModelItemID, false);

                    rs = ModelItems.Select("FillModelItemID='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillModelItemID", _ModelItemID, _newModelItemID, false);

                    _dr["ModelItemID"] = _newModelItemID;
                    _dr["ModelID"] = newModelID;
                    //
                }



                rows = ModelTabs.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelTabID = _dr["ModelTabID"].ToString();
                    string _newModelTabID = Guid.NewGuid().ToString();
                    _dr["ModelTabID"] = _newModelTabID;

                    rows = Models.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelPanels.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelItems.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    _dr["ModelID"] = newModelID;
                }


                rows = ModelPanels.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelPanelID = _dr["ModelPanelID"].ToString();
                    string _newModelPanelID = Guid.NewGuid().ToString();
                    _dr["ModelPanelID"] = _newModelPanelID;

                    rows = Models.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    rows = ModelItems.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    _dr["ModelID"] = newModelID;
                }




            }
            #endregion

            //eBase.PrintDataTable(Models);
            //eBase.PrintDataTable(ModelItems);
            //eBase.PrintDataTable(ModelTabs);
            //eBase.PrintDataTable(ModelPanels);

            #region 生成XML
            XmlDocument doc = new XmlDocument();
            Models.ExtendedProperties.Add("name", "a_eke_sysModels");
            doc.appendData(Models);
            ModelItems.ExtendedProperties.Add("name", "a_eke_sysModelItems");
            doc.appendData(ModelItems);
            //eBase.Writeln("a_eke_sysModelTabs");
            //eBase.PrintDataTable(ModelTabs);
            ModelTabs.ExtendedProperties.Add("name", "a_eke_sysModelTabs");
            doc.appendData(ModelTabs);

            //eBase.Writeln("a_eke_sysModelPanels");
            //eBase.PrintDataTable(ModelPanels);
            ModelPanels.ExtendedProperties.Add("name", "a_eke_sysModelPanels");
            doc.appendData(ModelPanels);
            #endregion

            XmlNode node = doc.SelectSingleNode("/root/data");
            if (node != null)
            {
                foreach (XmlNode _node in node.ChildNodes)
                {
                    DataTable dt = _node.ChildNodes.toDataTable();
                    eBase.DataBase.SchemaImport(dt);

                }
            }
            eBase.clearDataCache(); //清除所有缓存
        }
        private void CopyModel(string modelid)
        {
            XmlDocument doc = new XmlDocument();
            string ids = getids(modelid);
            ids = "'" + ids.Replace(",", "','") + "'";
            //Response.Write(ids);
          

            #region  生成关系
            eList a_eke_sysModels = new eList("a_eke_sysModels");
            a_eke_sysModels.Where.Add("deltag=0");
            //a_eke_sysModels.Where.Add("modelid='" + modelid + "'");
            a_eke_sysModels.Where.Add("modelid in (" + ids + ")");
            //a_eke_sysModels.Where.Add("modelid in ('7254820c-df55-4655-be0a-f14527556493','bf9da797-4b14-488f-9297-b7599edfe5cc')"); //'5ac4ba59-a545-467e-997d-7721802a403b','C6399A56-C165-4610-AE02-F593DBE8226A'



            eList a_eke_sysActions = new eList("a_eke_sysActions");
            a_eke_sysActions.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysActions);

            eList a_eke_sysCheckUps = new eList("a_eke_sysCheckUps");
            a_eke_sysCheckUps.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysCheckUps);

            eList a_eke_sysConditions = new eList("a_eke_sysConditions");
            a_eke_sysConditions.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysConditions);

            eList a_eke_sysModelConditions = new eList("a_eke_sysModelConditions");
            a_eke_sysModelConditions.Where.Add("deltag=0");
            eList a_eke_sysModelConditionItems = new eList("a_eke_sysModelConditionItems");
            a_eke_sysModelConditionItems.Where.Add("deltag=0");
            a_eke_sysModelConditions.Add(a_eke_sysModelConditionItems);
            a_eke_sysModels.Add(a_eke_sysModelConditions);


            eList a_eke_sysModelItems = new eList("a_eke_sysModelItems");
            a_eke_sysModelItems.Where.Add("deltag=0");
            //a_eke_sysModelItems.Rows = 1;
            a_eke_sysModels.Add(a_eke_sysModelItems);

            eList a_eke_sysModelTabs = new eList("a_eke_sysModelTabs");
            a_eke_sysModelTabs.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelTabs);

            eList a_eke_sysModelPanels = new eList("a_eke_sysModelPanels");
            a_eke_sysModelPanels.Where.Add("deltag=0");
            a_eke_sysModels.Add(a_eke_sysModelPanels);




            eList a_eke_sysReports = new eList("a_eke_sysReports");
            a_eke_sysReports.Where.Add("deltag=0");
            eList a_eke_sysReportItems = new eList("a_eke_sysReportItems");
            a_eke_sysReportItems.Where.Add("deltag=0");
            //a_eke_sysReportItems.Rows = 5;
            a_eke_sysReports.Add(a_eke_sysReportItems);
            a_eke_sysModels.Add(a_eke_sysReports);
            #endregion
            #region 获取数据
            //eBase.Writeln("a_eke_sysModels");
            DataTable Models = a_eke_sysModels.getDataTable();
            //Models.Columns.Remove("addTime");
            //eBase.PrintDataTable(Models);     
          

            //eBase.Writeln("a_eke_sysActions");
            DataTable Actions = a_eke_sysActions.getDataTable();

            //eBase.PrintDataTable(Actions);

            // eBase.Writeln("a_eke_sysCheckUps");
            DataTable CheckUps = a_eke_sysCheckUps.getDataTable();

            //eBase.PrintDataTable(CheckUps);



            //eBase.Writeln("a_eke_sysModelConditions");
            DataTable ModelConditions = a_eke_sysModelConditions.getDataTable();

            //eBase.PrintDataTable(ModelConditions);

            //eBase.Writeln("a_eke_sysModelConditionItems");
            DataTable ModelConditionItems = a_eke_sysModelConditionItems.getDataTable();

            //eBase.PrintDataTable(ModelConditionItems);

            //eBase.Writeln("a_eke_sysModelItems");
            DataTable ModelItems = a_eke_sysModelItems.getDataTable();
            //eBase.PrintDataTable(ModelItems);


            //eBase.Writeln("a_eke_sysModelTabs");
            DataTable ModelTabs = a_eke_sysModelTabs.getDataTable();
            //eBase.PrintDataTable(ModelTabs);

            //eBase.Writeln("a_eke_sysModelPanels");
            DataTable ModelPanels = a_eke_sysModelPanels.getDataTable();
            //eBase.PrintDataTable(ModelPanels);


            //eBase.Writeln("a_eke_sysReports");
            DataTable Reports = a_eke_sysReports.getDataTable();
            //eBase.PrintDataTable(Reports);

            //eBase.Writeln("a_eke_sysReportItems");
            DataTable ReportItems = a_eke_sysReportItems.getDataTable();
            //eBase.PrintDataTable(ReportItems);
            #endregion
            #region 数据处理
            DataRow[] rows;
            foreach (DataRow dr in Models.Rows)
            {
                string ModelID = dr["ModelID"].ToString();
                if (Models.Columns.Contains("addtime"))
                {
                    dr["addtime"] = DateTime.Now;
                }
                if (modelid == ModelID) //主模块
                {
                    string name = eParameters.QueryString("name");
                    if (name.Length > 0)
                    {
                        dr["mc"] = name;
                    }
                    else
                    {
                        dr["mc"] = dr["mc"].ToString() + " - 复件";
                    }
                    string code = eParameters.QueryString("code");
                    string oldcode = dr["code"].ToString();
                    if (code.Length > 0 && oldcode.Length > 0 && code.ToLower()!=oldcode.ToLower())
                    {
                        sql = eBase.DataBase.getTableSql(oldcode);
                        sql = System.Text.RegularExpressions.Regex.Replace(sql, "\\[" + oldcode + "\\]", "[" + code + "]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        sql = System.Text.RegularExpressions.Regex.Replace(sql, "'" + oldcode + "'", "'" + code + "'", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                        eBase.DataBase.Execute(sql);
                        dr["code"] = code;
                    }
                }
                else
                {
                    string code = eParameters.QueryString("code");
                    if (code.Length > 0)
                    {
                        string oldcode = dr["code"].ToString();
                        if (oldcode.Length > 0 && oldcode.ToLower().IndexOf("a_eke_sys") == -1)
                        {
                            code = oldcode + "_Copy";
                            sql = eBase.DataBase.getTableSql(oldcode);
                            sql = System.Text.RegularExpressions.Regex.Replace(sql, "\\[" + oldcode + "\\]", "[" + code + "]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            sql = System.Text.RegularExpressions.Regex.Replace(sql, "'" + oldcode + "'", "'" + code + "'", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                            eBase.DataBase.Execute(sql);
                            dr["code"] = code;
                        }
                    }
                }
                string newModelID = Guid.NewGuid().ToString();
                dr["ModelID"] = newModelID;

                rows = Models.Select("ParentID='" + ModelID + "'");
                rows.UpdateForeignKey("ParentID", ModelID, newModelID, false);


                rows = ModelItems.Select("BindModelID='" + ModelID + "'");
                rows.UpdateForeignKey("BindModelID", ModelID, newModelID, true);

                rows = ModelItems.Select("FillModelID='" + ModelID + "'");
                rows.UpdateForeignKey("FillModelID", ModelID, newModelID, true);


                // eBase.Writeln(ModelID + " to " + newModelID);

                rows = Actions.Select("ModelID='" + ModelID + "'");
                rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);

                rows = CheckUps.Select("ModelID='" + ModelID + "'");
                rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);




                rows = ModelConditions.Select("ModelID='" + ModelID + "'");
                //rows.UpdateForeignKey("ModelID", newModelID, true);
                foreach (DataRow _dr in rows)
                {
                    string _ModelConditionID = _dr["ModelConditionID"].ToString();
                    string _newModelConditionID = Guid.NewGuid().ToString();
                    _dr["ModelConditionID"] = _newModelConditionID;

                    rows = ModelConditionItems.Select("ModelConditionID='" + _ModelConditionID + "'");
                    rows.UpdateForeignKey("ModelConditionID", _ModelConditionID, _newModelConditionID, true);
                    rows.UpdateForeignKey("ModelID", ModelID, newModelID, false);


                    _dr["ModelID"] = newModelID;
                }


                rows = ModelItems.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelItemID = _dr["ModelItemID"].ToString();
                    string _newModelItemID = Guid.NewGuid().ToString();
                    DataRow[] rs = ModelItems.Select("FillItem='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillItem", _ModelItemID, _newModelItemID, false);

                    rs = ModelItems.Select("FillModelItemID='" + _ModelItemID + "'");
                    rs.UpdateForeignKey("FillModelItemID", _ModelItemID, _newModelItemID, false);

                    _dr["ModelItemID"] = _newModelItemID;
                    _dr["ModelID"] = newModelID;
                    //
                }
                //rows.UpdateForeignKey("ModelID",ModelID, newModelID,true);
                //eBase.PrintDataRow(rows);
                //eBase.PrintDataTable(ModelItems);




                rows = ModelTabs.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelTabID = _dr["ModelTabID"].ToString();
                    string _newModelTabID = Guid.NewGuid().ToString();
                    _dr["ModelTabID"] = _newModelTabID;

                    rows = Models.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelPanels.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    rows = ModelItems.Select("ModelTabID='" + _ModelTabID + "'");
                    rows.UpdateForeignKey("ModelTabID", _ModelTabID, _newModelTabID, false);

                    _dr["ModelID"] = newModelID;
                }


                rows = ModelPanels.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ModelPanelID = _dr["ModelPanelID"].ToString();
                    string _newModelPanelID = Guid.NewGuid().ToString();
                    _dr["ModelPanelID"] = _newModelPanelID;

                    rows = Models.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    rows = ModelItems.Select("ModelPanelID='" + _ModelPanelID + "'");
                    rows.UpdateForeignKey("ModelPanelID", _ModelPanelID, _newModelPanelID, false);

                    _dr["ModelID"] = newModelID;
                }
                //rows.UpdateForeignKey("ModelID", ModelID, newModelID, true);

                rows = Reports.Select("ModelID='" + ModelID + "'");
                foreach (DataRow _dr in rows)
                {
                    string _ReportID = _dr["ReportID"].ToString();
                    string _newReportID = Guid.NewGuid().ToString();
                    _dr["ReportID"] = _newReportID;



                    rows = ReportItems.Select("ReportID='" + _ReportID + "'");
                    rows.UpdateForeignKey("ReportID", _ReportID, _newReportID, true);
                    _dr["ModelID"] = newModelID;
                }
            }
            #endregion
            #region 生成XML
            //eBase.Write("<hr>");
            //eBase.Writeln("a_eke_sysModels");
           // eBase.PrintDataTable(Models);
            Models.ExtendedProperties.Add("name", "a_eke_sysModels");
            doc.appendData(Models);
           


            //eBase.Writeln("a_eke_sysActions");
            //eBase.PrintDataTable(Actions);
            Actions.ExtendedProperties.Add("name", "a_eke_sysActions");
            doc.appendData(Actions);


            //eBase.Writeln("a_eke_sysCheckUps");
            //eBase.PrintDataTable(CheckUps);
            CheckUps.ExtendedProperties.Add("name", "a_eke_sysCheckUps");
            doc.appendData(CheckUps);



            //eBase.Writeln("a_eke_sysModelConditions");
            //eBase.PrintDataTable(ModelConditions);
            ModelConditions.ExtendedProperties.Add("name", "a_eke_sysModelConditions");
            doc.appendData(ModelConditions);


            //eBase.Writeln("a_eke_sysModelConditionItems");
            //eBase.PrintDataTable(ModelConditionItems);
            ModelConditionItems.ExtendedProperties.Add("name", "a_eke_sysModelConditionItems");
            doc.appendData(ModelConditionItems);



            //eBase.Writeln("a_eke_sysModelItems");
            //eBase.PrintDataTable(ModelItems);
            ModelItems.ExtendedProperties.Add("name", "a_eke_sysModelItems");
            doc.appendData(ModelItems);




            //eBase.Writeln("a_eke_sysModelTabs");
            //eBase.PrintDataTable(ModelTabs);
            ModelTabs.ExtendedProperties.Add("name", "a_eke_sysModelTabs");
            doc.appendData(ModelTabs);



            //eBase.Writeln("a_eke_sysModelPanels");
            //eBase.PrintDataTable(ModelPanels);
            ModelPanels.ExtendedProperties.Add("name", "a_eke_sysModelPanels");
            doc.appendData(ModelPanels);

            //eBase.Writeln("a_eke_sysReports");
            //eBase.PrintDataTable(Reports);
            Reports.ExtendedProperties.Add("name", "a_eke_sysReports");
            doc.appendData(Reports);

            //eBase.Writeln("a_eke_sysReportItems");
            //eBase.PrintDataTable(ReportItems);
            ReportItems.ExtendedProperties.Add("name", "a_eke_sysReportItems");
            doc.appendData(ReportItems);

            #endregion
           // eBase.WriteHTML(doc.InnerXml);
            XmlNode node = doc.SelectSingleNode("/root/data");
            if (node != null)
            {
                foreach (XmlNode _node in node.ChildNodes)
                {
                    DataTable dt = _node.ChildNodes.toDataTable();
                   
                    //eBase.Writeln(dt.Rows.Count.ToString());
                    //eBase.PrintDataTable(dt);

                    eBase.DataBase.SchemaImport(dt);
                    //Access.SchemaImport(dt);
                }
            }
            eBase.clearDataCache(); //清除所有缓存

        }
        protected void Action_Actioning(string Actioning)
        {
            if (Actioning == "add" || Actioning == "edit")
            {

                //eBase.Print(eBase.ModelType.toRows().Select("value in ('1','3','4','5','6','7','10','11')"));
                f9.Options = eBase.addModelType.ToJson();
                if (1 == 1)
                {
                    StringBuilder sb = new StringBuilder();
                    //DataTable tb = eBase.DataBase.getDataTable("SELECT id,name FROM sysobjects where category=0 and xtype='U' order by crdate");
                    string sql = "SELECT id,name FROM sysobjects where xtype='U' "; //name!='dtproperties' and   
                    sql += " and (charindex('a_eke_sys',lower(name))=0 or lower(name)='a_eke_sysusers' or lower(name)='a_eke_syspowers' or lower(name)='a_eke_systokens' or lower(name)='a_eke_sysroles' or lower(name)='a_eke_sysdataviews' or lower(name)='a_eke_sysdatacontents'  )";
                    sql += " and name not in (" + eBase.getSystemTables() + ")";
                    sql += " order by name";//crdate";
                    //eBase.Writeln(sql);
                    //eBase.End();
                    DataTable tb = eBase.DataBase.getDataTable(sql);
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {

                        sb.Append("<option value=\"" + tb.Rows[i]["name"].ToString() + "\"" + (tb.Rows[i]["name"].ToString() == edt.Fields["code"].ToString() ? " selected=\"true\"" : "") + ">" + tb.Rows[i]["name"].ToString() + "</option>\r\n");
                    }
                    LitTable.Text = sb.ToString();
                }

                LitParent.Text = getModelTree("", "", f7.Value.ToString());
            }
            #region 添加步骤
            if (Actioning == "createstep")
            {
                CreateStep(Request.QueryString["ID"].ToString());
                if (Request.ServerVariables["HTTP_REFERER"] != null)
                {
                    Response.Redirect(Request.ServerVariables["HTTP_REFERER"].ToString(), true);
                }
                else
                {
                    Response.Redirect("Models.aspx", true);
                }
                Response.End();
            }
            #endregion
            #region 复制功能
            if (Actioning == "copy")
            {
                CopyModel(Request.QueryString["ID"].ToString());
                if (Request.ServerVariables["HTTP_REFERER"] != null)
                {
                    Response.Redirect(Request.ServerVariables["HTTP_REFERER"].ToString(), true);
                }
                else
                {
                    Response.Redirect("Models.aspx", true);
                }
                Response.End();
            }
            if (Actioning == "copy_bak")
            {
                /*
                eMTable Model = new eMTable("a_eke_sysModels");
                Model.Where.Add("ModelID='" + Request.QueryString["ID"].ToString() + "'");


                eMTable sModel = new eMTable("a_eke_sysModels");
                Model.Add(sModel);

                eMTable sModel1 = new eMTable("a_eke_sysModels");
                sModel.Add(sModel1);

                eMTable sModel2 = new eMTable("a_eke_sysModels");
                sModel1.Add(sModel2);

                eMTable ModelTabs = new eMTable("a_eke_sysModelTabs");
                Model.Add(ModelTabs);
                sModel.Add(ModelTabs);
                sModel1.Add(ModelTabs);
                sModel2.Add(ModelTabs);


                eMTable ModelPanels = new eMTable("a_eke_sysModelPanels");
                Model.Add(ModelPanels);
                sModel.Add(ModelPanels);
                sModel1.Add(ModelPanels);
                sModel2.Add(ModelPanels);

                eMTable action = new eMTable("a_eke_sysActions");
                Model.Add(action);
                sModel.Add(action);
                sModel1.Add(action);
                sModel2.Add(action);

                string ct = eBase.DataBase.getValue("select count(1) from a_eke_sysCheckUps where ModelID='" + Request.QueryString["ID"].ToString() + "'");
                if (ct.Length > 0 && ct != "0")
                {

                    eMTable CheckUps = new eMTable("a_eke_sysCheckUps");
                    eMTable CheckupRecords = new eMTable("a_eke_sysCheckupRecords");
                    CheckUps.Add(CheckupRecords);
                    Model.Add(CheckUps);
                }


                eMTable Conditions = new eMTable("a_eke_sysConditions");
                Model.Add(Conditions);
                sModel.Add(Conditions);
                sModel1.Add(Conditions);
                sModel2.Add(Conditions);

                eMTable Conds = new eMTable("a_eke_sysModelConditions");
                eMTable CondItems = new eMTable("a_eke_sysModelConditionItems");
                Conds.Add(CondItems);
                Model.Add(Conds);
                sModel.Add(Conds);
                sModel1.Add(Conds);
                sModel2.Add(Conds);


                eMTable Items = new eMTable("a_eke_sysModelItems");
                Model.Add(Items);
                sModel.Add(Items);
                sModel1.Add(Items);
                sModel2.Add(Items);


                eMTable Reports = new eMTable("a_eke_sysReports");
                eMTable ReportItems = new eMTable("a_eke_sysReportItems");
                Reports.Add(ReportItems);
                Model.Add(Reports);



                Model.Copy();
                eBase.DataBase.Execute("update a_eke_sysModels set MC='复件-' + MC where ModelID='" + Model.ID + "'");
                //eBase.Writeln(Model.ID);
                //eBase.End();


                if (Request.ServerVariables["HTTP_REFERER"] != null)
                {
                    Response.Redirect(Request.ServerVariables["HTTP_REFERER"].ToString(), true);
                }
                else
                {
                    Response.Redirect("Models.aspx", true);
                }
                */
            }
            #endregion
            switch (Actioning)
            {
                case "":
                    List();
                    break;
                case "add":
                    break;
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Master == null) return;
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = "模块管理 - " + eConfig.manageName(); 
            }
        }
    }
}